package com.ep.thirdPlatformProject.system.util;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.google.gson.JsonParseException;
import com.xxl.job.core.biz.model.ReturnT;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class OkHttpUtils {
    private static volatile OkHttpClient.Builder okHttpClient = null;

    // 使用ConcurrentHashMap来存储Semaphore实例，以减少锁的竞争
    private static final ConcurrentHashMap<Class<?>, Semaphore> semaphoreMap = new ConcurrentHashMap<>();
    private Map<String, String> headerMap;
    private Map<String, Object> paramMap;


    private String url;
    private Request.Builder request;


    private static final Logger logger = LoggerFactory.getLogger(OkHttpUtils.class);

    /**
     * 初始化okHttpClient，并且允许https访问
     */
    private OkHttpUtils() {
        if (okHttpClient == null) {
            synchronized (OkHttpUtils.class) {
                if (okHttpClient == null) {
                    TrustManager[] trustManagers = buildTrustManagers();
                    okHttpClient = new OkHttpClient.Builder()
                            .connectTimeout(15, TimeUnit.SECONDS)
                            .writeTimeout(20, TimeUnit.SECONDS)
                            .readTimeout(20, TimeUnit.SECONDS)
                            .sslSocketFactory(createSSLSocketFactory(trustManagers), (X509TrustManager) trustManagers[0])
                            .hostnameVerifier((hostName, session) -> true)
                            .retryOnConnectionFailure(true);
                }
            }
        }
    }

    /**
     * 用于异步请求时，控制访问线程数，返回结果
     *
     * @return Semaphore
     */
    private static Semaphore getSemaphoreInstance() {
        // 使用computeIfAbsent方法来原子化地检查和初始化Semaphore实例
        return semaphoreMap.computeIfAbsent(OkHttpUtils.class, k -> {
            // 考虑到异常情况，添加try-catch块
            try {
                // 调整Semaphore的初始许可量为1，以避免永久阻塞的情况
                return new Semaphore(1);
            } catch (Exception e) {
                // 在发生异常时，记录日志或进行其他适当的处理
                // 注意：这里需要根据实际情况选择合适的日志记录方式
                System.err.println("Error initializing semaphore: " + e.getMessage());
                return null;
            }
        });
    }

    /**
     * 创建OkHttpUtils
     *
     * @return OkHttpUtils
     */
    public static OkHttpUtils builder() {
        return new OkHttpUtils();
    }

    /**
     * 添加url
     *
     * @param url url
     * @return OkHttpUtils
     */
    public OkHttpUtils url(String url) {
        this.url = url;
        return this;
    }

    /**
     * 添加参数
     *
     * @param key   参数名
     * @param value 参数值
     * @return OkHttpUtils
     */
    public OkHttpUtils addParam(String key, Object value) {
        if (paramMap == null) {
            paramMap = new ConcurrentHashMap<>(16);
        }
        paramMap.put(key, value);
        return this;
    }

    /**
     * 向请求中添加JSON参数。
     * 该方法会遍历传入对象的所有字段，将非空字段的名称和值添加到请求参数中。
     * 注意：此方法适用于需要将对象作为JSON参数进行网络请求的情况。
     *
     * @param object 需要添加为参数的对象。对象的字段会被转换为请求参数。
     * @return 返回OkHttpUtils的实例，支持链式调用。
     * @throws JsonParseException 如果对象字段不是有效的JSON格式，会抛出此异常。
     * @throws RuntimeException   如果处理过程中发生异常，会抛出此运行时异常。
     */
    public OkHttpUtils addJsonParam(@NotNull Object object) {

        if (paramMap == null) {
            paramMap = new ConcurrentHashMap<>(16); // 当paramMap为空时，初始化为容量为16的ConcurrentHashMap
        }
        try {

            Field[] declaredFields = object.getClass().getDeclaredFields(); // 获取对象的所有声明字段
            for (Field declaredField : declaredFields) {

                // 设置私有字段可访问，以读取其值
                if (Modifier.isPrivate(declaredField.getModifiers())) {
                    declaredField.setAccessible(true);
                }

                // 仅当字段值不为空时，将其添加到paramMap中
                if (ObjectUtil.isNotNull(declaredField.get(object))) {
                    Object obj = declaredField.get(object);
                    paramMap.put(declaredField.getName(), obj);
                }

            }
        } catch (Exception e) {
            // 处理过程中发生其他异常时的错误日志
            String errorMsg = "处理对象 " + object.getClass().getSimpleName() + " 时出错";
            logger.error("json转换失败,{}", errorMsg, e);
            throw new RuntimeException("json转换失败");
        }
        return this;
    }


    /**
     * 添加请求头
     *
     * @param key   参数名
     * @param value 参数值
     * @return OkHttpUtils
     */
    public OkHttpUtils addHeader(String key, String value) {
        if (headerMap == null) {
            headerMap = new ConcurrentHashMap<>(16);
        }
        headerMap.put(key, value);
        return this;
    }

    /**
     * 添加cookie
     *
     * @param cookie cookie
     * @return {@link OkHttpUtils}
     */
    public OkHttpUtils addCookie(String cookie) {
        okHttpClient.cookieJar(new CookieJar() {
            private final List<Cookie> cookies = new ArrayList<>();

            @Override
            public void saveFromResponse(@NotNull HttpUrl url, @NotNull List<Cookie> cookies) {
                this.cookies.addAll(cookies);
            }

            @NotNull
            @Override
            public List<Cookie> loadForRequest(@NotNull HttpUrl url) {
                return cookies;
            }
        }).addInterceptor(new CookieInterceptor(cookie));

        return this;
    }

    /**
     * 获取cookie
     *
     * @return {@link String}
     */
    public String getCookie() {
        setHeader(request);
        try {
            String cookie = "";
            try (Response response = okHttpClient.build().newCall(request.build()).execute()) {
                if (response.isSuccessful()) {//response 请求成功
                    ResponseBody body = response.body();
                    if (ObjectUtil.isNull(body)) {
                        throw new OKHttpRequestException("当前响应为空！");
                    }
                    validateCookieTrue(body.string());
                    Headers headers = response.headers();
                    List<String> cookies = headers.values("Set-Cookie");
                    if (!cookies.isEmpty()) {
                        String session = cookies.get(0);
                        if (!StrUtil.isEmptyIfStr(session)) {
                            int i = session.indexOf(";");
                            if (i >= 0) {
                                //最终获取到的cookie
                                cookie = session.substring(0, i);
                            }
                        }
                    }
                } else {
                    throw new OKHttpRequestException("获取cookie失败");
                }
            }
            return cookie;
        } catch (IOException e) {
            logger.error("请求失败：{}", e.getMessage(), e);
            throw new OKHttpRequestException("请求失败：" + e.getMessage(), e);
        }

    }


    /**
     * 验证cookie为真
     *
     * @param jsonString json
     */
    private void validateCookieTrue(String jsonString) {

        if (ObjectUtil.isNotEmpty(jsonString)) {
            ReturnT res = JSON.parseObject(jsonString, ReturnT.class);
            if (ReturnT.SUCCESS_CODE != res.getCode()) {
                throw new OKHttpRequestException("登录操作端系统异常，" + res.getMsg());
            }
        }

    }

    /**
     * 初始化get方法
     *
     * @return this
     */
    public OkHttpUtils get() {
        request = new Request.Builder().get();
        StringBuilder urlBuilder = new StringBuilder(url);
        if (paramMap != null) {
            urlBuilder.append("?");
            try {
                for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                    urlBuilder.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8)).
                            append("=").
                            append(URLEncoder.encode(String.valueOf(entry.getValue()), StandardCharsets.UTF_8)).
                            append("&");
                }
            } catch (Exception e) {
                logger.error("url encode error", e);
            }
            urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        }
        request.url(urlBuilder.toString());
        return this;
    }

    /**
     * 初始化post方法
     *
     * @param isJsonPost true等于json的方式提交数据，类似postman里post方法的raw
     *                   false等于普通的表单提交
     * @return OkHttpUtils
     */
    public OkHttpUtils post(boolean isJsonPost) {
        RequestBody requestBody;
        if (isJsonPost) {
            String json = "";
            if (paramMap != null) {
                json = JSON.toJSONString(paramMap);
            }
            MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
            requestBody = RequestBody.Companion.create(json, mediaType);

        } else {
            FormBody.Builder formBody = new FormBody.Builder();
            if (paramMap != null) {
                paramMap.forEach((k, v) -> {
                    formBody.add(k, String.valueOf(v));
                });
            }
            requestBody = formBody.build();
        }
        request = new Request.Builder().post(requestBody).url(url);
        return this;
    }

    /**
     * Post json请求
     *
     * @param jsonString json字符串
     * @return {@link OkHttpUtils}
     */
    public OkHttpUtils postJsonRequest(@NotNull String jsonString) {
        MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.Companion.create(jsonString, mediaType);
        request = new Request.Builder().post(requestBody).url(url);
        return this;
    }

    /**
     * 同步请求
     *
     * @return String
     */
    public String sync() {
        setHeader(request);
        try {
            try (Response response = okHttpClient.build().newCall(request.build()).execute()) {
                return response.body().string();
            }

        } catch (IOException e) {
            logger.error("同步请求失败：{}", e.getMessage(), e);
            throw new OKHttpRequestException("同步请求失败：" + e.getMessage(), e);
        }
    }

    /**
     * 异步请求，有返回值
     */
    public String async() {
        StringBuilder buffer = new StringBuilder();
        setHeader(request);
        okHttpClient.build().newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                buffer.append("请求出错：").append(e.getMessage());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                buffer.append(response.body().string());
                getSemaphoreInstance().release();
            }
        });
        try {
            getSemaphoreInstance().acquire();
        } catch (InterruptedException e) {
            logger.error("获取信号量失败：{}", e.getMessage(), e);
        }
        return buffer.toString();
    }

    /**
     * 异步请求，带有接口回调
     *
     * @param callBack callBack
     */
    public void async(ICallBack callBack) {
        setHeader(request);
        okHttpClient.build().newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                callBack.onFailure(call, e.getMessage());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                assert response.body() != null;
                callBack.onSuccessful(call, response.body().string());
            }
        });
    }

    /**
     * 为request添加请求头
     *
     * @param request request
     */
    private void setHeader(Request.Builder request) {
        if (headerMap != null) {
            try {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    request.addHeader(entry.getKey(), entry.getValue());
                }
            } catch (Exception e) {
                logger.error("添加请求头失败：{}", e.getMessage());
            }
        }
    }


    /**
     * 生成安全套接字工厂，用于https请求的证书跳过
     *
     * @return SSLSocketFactory
     */
    private static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustAllCerts) {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
            logger.error("初始化SSL失败：{}", e.getMessage());
        }
        return ssfFactory;
    }

    private static TrustManager[] buildTrustManagers() {
        return new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
    }

    /**
     * 自定义一个接口回调
     */
    public interface ICallBack {

        void onSuccessful(Call call, String data);

        void onFailure(Call call, String errorMsg);

    }


    public static class CookieInterceptor implements Interceptor {
        private final List<Cookie> cookies;

        public CookieInterceptor(List<Cookie> cookies) {
            this.cookies = cookies;
        }

        public CookieInterceptor(String cookie) {
            this.cookies = new ArrayList<>();
            cookies.add(new Cookie.Builder().name("JSESSIONID").value(cookie).build());
        }

        @NotNull
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request.Builder requestBuilder = chain.request().newBuilder();

            for (Cookie cookie : cookies) {
                requestBuilder.addHeader("Cookie", cookie.name() + "=" + cookie.value());
            }

            return chain.proceed(requestBuilder.build());
        }
    }

    public static class OKHttpRequestException extends RuntimeException {
        public OKHttpRequestException(String message) {
            super(message);
        }

        public OKHttpRequestException(String message, Throwable cause) {
            super(message, cause);
        }
    }


}